
package com.dog.basics.service.wishwash.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dog.basics.bean.dto.admin.wishwash.AdminDogHxFieldPriceAddDto;
import com.dog.basics.bean.model.sys.SysUserInfo;
import com.dog.basics.bean.model.wishwash.DogHxFieldPrice;
import com.dog.basics.bean.vo.admin.wishwash.AdminDogHxFieldPriceVo;
import com.dog.basics.common.constant.CommonConstants;
import com.dog.basics.common.util.PageParam;
import com.dog.basics.common.util.SpringContextUtils;
import com.dog.basics.dao.sys.SysUserInfoMapper;
import com.dog.basics.security.util.SecurityUtils;
import com.dog.basics.bean.dto.admin.wishwash.AdminDogHxFieldAddDto;
import com.dog.basics.bean.dto.admin.wishwash.AdminDogHxFieldEditDto;
import com.dog.basics.bean.dto.admin.wishwash.AdminDogHxFieldFromDto;
import com.dog.basics.bean.vo.admin.wishwash.AdminDogHxFieldVo;
import com.dog.basics.bean.vo.admin.wishwash.AdminDogHxFieldInfoVo;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

import com.dog.basics.service.sys.SysUserRoleService;
import com.dog.basics.service.wishwash.DogHxFieldPriceService;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dog.basics.bean.model.wishwash.DogHxField;
import com.dog.basics.dao.wishwash.DogHxFieldMapper;
import com.dog.basics.service.wishwash.DogHxFieldService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 场地信息
 *
 * @author cy code generator
 * @date 2021-07-09 17:40:28
 */
@Service
@AllArgsConstructor
public class DogHxFieldServiceImpl extends ServiceImpl<DogHxFieldMapper, DogHxField> implements DogHxFieldService {
    private final SysUserInfoMapper userInfoMapper;

    /**
     * @Description: 后台管理分页
     * @Param: status
     * @return: IPage
     * @author cy code generator
     * @date 2021-07-09 17:40:28
     */
    @Override
    public IPage<AdminDogHxFieldVo> getAdminPageList(PageParam page, AdminDogHxFieldFromDto obj) {
        if (!SecurityUtils.hasRole(CommonConstants.ROLE_ADMIN_CODE)) {
            // 判断代理商
            if (SecurityUtils.hasRole(CommonConstants.ROLE_AGENT_CODE)) {
                obj.setFieldAgentId(SecurityUtils.getSysUser().getUserId());
            }
            // 判断场地负责人
            if (SecurityUtils.hasRole(CommonConstants.ROLE_FIELD_CODE)) {
                obj.setFieldUserId(SecurityUtils.getSysUser().getUserId());
            }
        }
        // 后台管理 - 分页查询数据信息
        this.page(page, Wrappers.<DogHxField>lambdaQuery()
                .eq(ObjectUtil.isNotNull(obj.getFieldAgentId()), DogHxField::getFieldAgentId,obj.getFieldAgentId())
                .eq(ObjectUtil.isNotNull(obj.getFieldUserId()), DogHxField::getFieldUserId,obj.getFieldUserId())
                .like(StrUtil.isNotBlank(obj.getFieldName()), DogHxField::getFieldName, obj.getFieldName())
                .between(ObjectUtil.isNotNull(obj.getStartTime()) && ObjectUtil.isNotNull(obj.getEndTime()), DogHxField::getCreateTime, obj.getStartTime(), obj.getEndTime())
                .orderBy(Boolean.TRUE, obj.getIsOrderByAvg(), DogHxField::getCreateTime));
        // 格式化数据信息
        List<DogHxField> records = page.getRecords();
        page.setRecords(records.stream().map(e -> {
            // 数据信息转换
            AdminDogHxFieldVo objVo = BeanUtil.toBean(e, AdminDogHxFieldVo.class);
            // 下面自定义格式化返回数据
            SysUserInfo userInfo = userInfoMapper.selectById(e.getFieldAgentId());
            objVo.setAgenName(ObjectUtil.isNotNull(userInfo) ? userInfo.getRealName() : "");
            SysUserInfo userInfo1 = userInfoMapper.selectById(e.getFieldUserId());
            objVo.setFieldUserName(ObjectUtil.isNotNull(userInfo1) ? userInfo1.getRealName() : "");
            return objVo;
        }).collect(Collectors.toList()));
        // 数据返回
        return page;
    }


    /**
     * @Description: 后台管理查询详情
     * @Param: obj
     * @return: Boolean
     * @author cy code generator
     * @date 2021-07-09 17:40:28
     */
    @Override
    public AdminDogHxFieldInfoVo getAdminObjXq(Long id) {
        // 后台管理 - 查询数据信息是否存在
        DogHxField obj = this.getById(id);
        // 判断数据是否存在
        Validator.validateNotNull(obj, "common.noData");
        // 数据信息格式化 - 返回
        AdminDogHxFieldInfoVo objVo = BeanUtil.toBean(obj, AdminDogHxFieldInfoVo.class);
        // 查询价格信息
        List<DogHxFieldPrice> fieldPrices = SpringContextUtils.getBean(DogHxFieldPriceService.class).list(Wrappers.<DogHxFieldPrice>lambdaQuery().eq(DogHxFieldPrice::getFileldId, obj.getId()));
        List<AdminDogHxFieldPriceVo> collect = fieldPrices.stream().map(e -> {
            AdminDogHxFieldPriceVo hxFieldPriceVo = BeanUtil.toBean(e, AdminDogHxFieldPriceVo.class);
            return hxFieldPriceVo;
        }).collect(Collectors.toList());
        objVo.setAdminDogHxFieldPriceVos(collect);
        return objVo;
    }


    /**
     * @Description: 后台管理增加
     * @Param: obj
     * @return: Boolean
     * @author cy code generator
     * @date 2021-07-09 17:40:28
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveAdminObj(AdminDogHxFieldAddDto obj) {
        // 校验参数
        isAddEditVa(obj);
        // 后台管理 - 数据信息转换
        DogHxField objAdd = BeanUtil.toBean(obj, DogHxField.class);
        // 数据信息补充
        objAdd.setCreateTime(DateUtil.currentSeconds());
        objAdd.setCreateBy(SecurityUtils.getSysUser().getUserId());
        // 执行添加数据信息
        Validator.validateTrue(this.save(objAdd), "common.save");
        // 添加场地组价格信息
        Boolean aBoolean = addHxFieldPrices(objAdd, obj.getHxFieldPriceDtos());
        Validator.validateTrue(aBoolean, "common.save");
        return Boolean.TRUE;
    }


    /**
     * @Description: 后台管理修改
     * @Param: obj
     * @return: Boolean
     * @author cy code generator
     * @date 2021-07-09 17:40:28
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editAdminObj(AdminDogHxFieldEditDto obj) {
        // 校验参数
        isAddEditVa(obj);
        // 查询数据信息是否存在
        DogHxField objInfo = this.getById(obj.getId());
        // 判断数据是否存
        Validator.validateNotNull(objInfo, "无此数据");
        // 数据信息转换
        DogHxField editObj = BeanUtil.toBean(obj, DogHxField.class);
        // 补充数据信息
        editObj.setUpdateTime(DateUtil.currentSeconds());
        editObj.setUpdateBy(SecurityUtils.getSysUser().getUserId());
        if (!SecurityUtils.hasRole(CommonConstants.ROLE_ADMIN_CODE)) {
            // 判断代理商
            if (SecurityUtils.hasRole(CommonConstants.ROLE_AGENT_CODE)) {
                obj.setFieldAgentId(SecurityUtils.getSysUser().getUserId());
                Validator.validateEqual(obj.getFieldAgentId(), objInfo.getFieldAgentId(), "Agent cannot be modified");
            }
            // 判断场地负责人
            if (SecurityUtils.hasRole(CommonConstants.ROLE_FIELD_CODE)) {
                Validator.validateEqual(SecurityUtils.getSysUser().getUserId(), objInfo.getFieldUserId(), "The person in charge cannot be modified");
                Validator.validateEqual(obj.getFieldAgentId(), objInfo.getFieldAgentId(), "Agent cannot be modified");
            }
        }
        // 执行修改信息
        Validator.validateTrue(this.updateById(editObj), "修改失败!");
        // 删除场地组信息
        SpringContextUtils.getBean(DogHxFieldPriceService.class).remove(Wrappers.<DogHxFieldPrice>lambdaQuery().eq(DogHxFieldPrice::getFileldId, obj.getId()));
        // 添加场地组价格信息
        Boolean aBoolean = addHxFieldPrices(objInfo, obj.getHxFieldPriceDtos());
        Validator.validateTrue(aBoolean, "common.save");
        return Boolean.TRUE;
    }

    /**
     * 校验参数 【添加|修改】
     *
     * @param obj
     * @return
     */
    private Boolean isAddEditVa(AdminDogHxFieldAddDto obj) {
        // 判断价格是否大于正确
        Validator.validateEqual(CollUtil.size(obj.getHxFieldPriceDtos()), 20, "fileLd.price.composition.error");
        // 判断代理商+场地分润比例相加是否大于1
        boolean lessOrEqual = NumberUtil.isLessOrEqual(NumberUtil.add(obj.getFieldAgentProfitSharingRatio(), obj.getFieldLocalProfitSharingRatio()), BigDecimal.ONE);
        Validator.validateTrue(lessOrEqual, "fileLd.sharingRatio.max");
        // 判断是否代理商
        Boolean isUserCode = SpringContextUtils.getBean(SysUserRoleService.class).getIsUserCode(obj.getFieldAgentId(), CommonConstants.ROLE_AGENT_CODE);
        Validator.validateTrue(isUserCode, "dev.choice.noAgent");
        // 判断是否场地负责人
        Boolean isUserFileLdCode = SpringContextUtils.getBean(SysUserRoleService.class).getIsUserCode(obj.getFieldUserId(), CommonConstants.ROLE_FIELD_CODE);
        Validator.validateTrue(isUserFileLdCode, "fileLd.chouce.noFileLdUser");
        return Boolean.TRUE;
    }

    /**
     * @Description: 删除
     * @Param: ids
     * @return: Boolean
     * @author cy code generator
     * @date 2021-07-09 17:40:28
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteObj(Long id) {
        // 查询数据信息 - 根据标识
        DogHxField objInfo = this.getById(id);
        // 判断数据信息是否
        Validator.validateNotNull(objInfo, "无此数据");
        // 执行删除数据信息
        Validator.validateTrue(this.removeById(id), "删除失败!");
        return Boolean.TRUE;
    }

    /**
     * @功能描述: 添加场地组价格
     * @author He
     * @date 2021/7/19
     */
    private Boolean addHxFieldPrices(DogHxField obj, List<AdminDogHxFieldPriceAddDto> hxFieldPriceDtos) {
        // 判断场地的价格信息
        List<DogHxFieldPrice> hxFieldPrices = CollUtil.newArrayList();
        Integer devTypeLen = 2;
        for (Integer i = 0; i < devTypeLen; i++) {
            // 声明 大小类型
            Integer nodeDevSize = 5;
            for (Integer i1 = 0; i1 < nodeDevSize; i1++) {
                // 声明水温
                Integer nodeTemperatureOption = 3;
                // 实例化场地价格实体
                DogHxFieldPrice fieldPrice = new DogHxFieldPrice();
                fieldPrice.setFileldId(obj.getId());
                fieldPrice.setDevType(i);
                fieldPrice.setNodeDevSize(i1);
                fieldPrice.setCreateBy(SecurityUtils.getSysUser().getUserId());
                fieldPrice.setCreateTime(DateUtil.currentSeconds());
                // 判断是否洗衣机
                if (Validator.equal(i, 0)) {
                    // 循环添加洗衣机并且获取价格
                    for (Integer i3 = 0; i3 < nodeTemperatureOption; i3++) {
                        DogHxFieldPrice fieldPrices = BeanUtil.toBean(fieldPrice, DogHxFieldPrice.class);
                        fieldPrices.setNodeTemperatureOption(i3);
                        selectVenueGroupPrice(hxFieldPriceDtos, i, i1, i3,fieldPrices);
                        hxFieldPrices.add(fieldPrices);
                    }
                } else {
                    // 烘干机添加
                    fieldPrice.setNodeTemperatureOption(5);
                    selectVenueGroupPrice(hxFieldPriceDtos, i, i1, null,fieldPrice);
                    hxFieldPrices.add(fieldPrice);
                }
            }
        }
        // 添加场地价格组
        boolean b = SpringContextUtils.getBean(DogHxFieldPriceService.class).saveBatch(hxFieldPrices);
        Validator.validateTrue(b, "common.save");
        return Boolean.TRUE;
    }

    /**
     * @功能描述: 获取价格
     * @author He
     * @date 2021/7/19
     */
    private void selectVenueGroupPrice(List<AdminDogHxFieldPriceAddDto> dtos, Integer devType, Integer nodeSize, Integer wd, DogHxFieldPrice fieldPrice) {
        // 循环查询价格
        for (int i = 0; i < dtos.size(); i++) {
            // 转换实体
            AdminDogHxFieldPriceAddDto fieldPriceAddDto = dtos.get(i);
            // 判断是否选择的价格
            if (Validator.equal(fieldPriceAddDto.getDevType(), devType) && Validator.equal(fieldPriceAddDto.getNodeDevSize(), nodeSize)) {
                if (Validator.equal(devType, 0)) {
                    if (Validator.equal(fieldPriceAddDto.getNodeTemperatureOption(), wd)) {
                        fieldPrice.setPrice(fieldPriceAddDto.getPrice());
                    }
                } else {
                    fieldPrice.setPrice(fieldPriceAddDto.getPrice());
                    fieldPrice.setNodeTemperatureOption(fieldPriceAddDto.getNodeTemperatureOption());
                }
            }
        }
        if (ObjectUtil.isNull(fieldPrice.getPrice())) {
            fieldPrice.setPrice(BigDecimal.ZERO);
        }
    }
}
